﻿namespace Bon.It.Server
{
    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Collections.Generic;

    using Bon_It.Model;
    using Bon_It.Model.TransferObjects;

    public partial class ContractManager
    {
        #region Implementation of ICashierMethods

        /// <summary>
        /// Debits the specified items.
        /// </summary>
        /// <param name="items">The items.</param>
        /// <param name="information">The information.</param>
        public void Debit(BookingItem[] items, DebitInformation information)
        {
            using(var context = this.GetDataContext())
            {
                Belege beleg = new Belege
                    {
                        DebitType = information.DebitType.ToString(),
                        Total = items.Sum(i => i.Total),
                        Given = information.Given,
                        Stamp = DateTime.Now,

                        // Set the default cashier!
                        fkKassiererID = 1
                    };


                context.Belege.InsertOnSubmit(beleg);
                //context.SubmitChanges();
                foreach(BookingItem item in items)
                {
                    // try to find the articel number, 
                    // for the special articles there wouldn't be 
                    // needed any amound decrements.
                    var foundArticle = this.GetArticleById(item.ArticleID);
                    if (foundArticle != null)
                    {
                        // Article is found, so decrement the ammount
                        foundArticle.Bestand -= item.Amount;
                    }
                    // Add a bill Item 
                    Rechnung billItem = new Rechnung
                        {
                            Menge = item.Amount,
                            VKPreis = item.Price,
                            fkArtikel = item.ArticleID,
                            Deleted = false,
                            Belege = beleg
                        };
                    context.Rechnung.InsertOnSubmit(billItem);
                }
                context.SubmitChanges();
            }
        }

        #endregion
    }
}
